//
//  KABThemeListVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/17.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABThemeListVC.h"
#import "KABHpUserWallCCell.h"
#import "KABThemeMallCRView.h"
#import "KABThemeMallFooterCRView.h"
#import "KABThemePreviewVC.h"
#import <MJRefresh.h>
#import "KABModel.h"
#import "XDAFNetworking.h"
#import "GlobalHeader.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "ThemeManager.h"
#import <UIScrollView+EmptyDataSet.h>

@interface KABThemeListVC ()<UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>

@property (weak, nonatomic) IBOutlet UICollectionView *collectionView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (strong, nonatomic) KABSkinClass *skinClass;

@end

static NSString *const kReuseCellId = @"KABHpUserWallCCell";
static NSInteger const kRequestSkinClassSize = 20;

@implementation KABThemeListVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (void)initNavigationBar {
    self.navigationItem.title = (self.viewType == KABThemeListTypeMine) ? @"我的" : self.skinClassTitle;
    
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    if (self.viewType == KABThemeListTypeMine) {
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"恢复默认" style:UIBarButtonItemStylePlain target:self action:@selector(resetBarBtnItemTapped:)];
    }
}

- (void)initSubViews {
    UINib *cellNib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.collectionView registerNib:cellNib forCellWithReuseIdentifier:kReuseCellId];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.emptyDataSetDelegate = self;
    self.collectionView.emptyDataSetSource = self;
    // 下拉刷新
    self.collectionView.mj_header = self.mj_header;
    self.collectionView.mj_footer = self.mj_footer;
    // 请求数据
    [self.collectionView.mj_header beginRefreshing];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self refreshWholeView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"空空如也" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
    return -100.0;
}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UICollectionViewDataSource
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.skinClass.skinpackage_list.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    KABHpUserWallCCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.item < self.skinClass.skinpackage_list.count) {
        [cell configViewWithSkinClassItem:self.skinClass.skinpackage_list[indexPath.item] index:0 totalCnt:0];
    }
    return cell;
}

//- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
//    if ([kind isEqualToString:UICollectionElementKindSectionHeader]) {
//        KABThemeMallCRView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:kReuseCRViewId forIndexPath:indexPath];
//        return header;
//    } else if ([kind isEqualToString:UICollectionElementKindSectionFooter]) {
//        KABThemeMallFooterCRView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:kReuseFooterId forIndexPath:indexPath];
//        return footer;
//    }
//    return nil;
//}

#pragma mark - <UICollectionViewDelegateFlowLayout>
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 45.0);
//}
//
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {
//    return CGSizeMake(CGRectGetWidth(self.view.bounds), 6.0);
//}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat width = (CGRectGetWidth(self.view.bounds) - 2*13 - 2 * 24) / 3.0;
    CGFloat height = width * 133.0 / 100.0;
    return CGSizeMake(width, height);
}

#pragma mark - UICollectionViewDelegate
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    KABThemePreviewVC *vc = [[KABThemePreviewVC alloc] init];
    vc.skinClassItem = self.skinClass.skinpackage_list[indexPath.item];
    [self showViewController:vc sender:nil];
}

#pragma mark - event response
- (void)resetBarBtnItemTapped:(UIBarButtonItem *)item {
    [[ThemeManager sharedManager] changeThemeWithThemeId:0];
    [self refreshWholeView];
}

#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.skinClass.totalLoad) {
        [self.collectionView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.collectionView.mj_footer resetNoMoreData];
    }
    
    [self.collectionView reloadData];
}

- (void)collectionViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.collectionView.mj_header endRefreshing];
    } else {
        [self.collectionView.mj_footer endRefreshing];
    }
}

- (void)collectionViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    if (self.viewType == KABThemeListTypeMine) {
        [self requestMineSkinWithHeader:isHeader];
    } else {
        [self requestSkinHpWithHeader:isHeader];
    }
}

- (KABSkinClass *)skinClassWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.skinClass;
    }
    
    KABSkinClass *temp = [KABSkinClass yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.skinClass;
    }
    
    if (AddMore && self.skinClass) {
        [self.skinClass addMoreWithData:temp];
    } else {
        self.skinClass = temp;
    }
    return self.skinClass;
}

#pragma mark - network request
- (void)requestSkinHpWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self collectionViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.skinClass.skinpackage_list.lastObject.skin_id;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(last_id) forKey:@"last_id"];
    [pars setObject:@(kRequestSkinClassSize) forKey:@"size"];
    [pars setObject:@(self.skinClass_id) forKey:@"class_id"];
    [pars setObject:@(1) forKey:@"platform_type"];      //!< 1---"iOS"
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiSkinList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Skin列表返回：%@", responseObject);
        [self collectionViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self skinClassWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Skin列表失败：%@", error);
        [self collectionViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestMineSkinWithHeader:(BOOL)isHeader {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self collectionViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger last_id = isHeader ? 0 : self.skinClass.skinpackage_list.lastObject.skin_id;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(last_id) forKey:@"last_id"];
    [pars setObject:@(kRequestSkinClassSize) forKey:@"size"];
    [pars setObject:@(1) forKey:@"platform_type"];      //!< 1---"iOS"
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiSkinOrderList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Skin列表返回：%@", responseObject);
        [self collectionViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self skinClassWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Skin列表失败：%@", error);
        [self collectionViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
